package org.mnj07.xml;

import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.ValidationEvent;
import javax.xml.bind.ValidationEventLocator;
import javax.xml.bind.util.ValidationEventCollector;

import org.mnj07.xml.directory.DirectoryType;
import org.mnj07.xml.directory.ObjectFactory;
import org.mnj07.xml.directory.PersonType;

public class JaxbDemo {

	public static void main(String[] args) {
		System.out.println("Starting ...");
		
		ObjectFactory objectFactory = new ObjectFactory();
		DirectoryType directoryType = objectFactory.createDirectoryType();
		
		PersonType person = objectFactory.createPersonType();
		person.setFirstName("John");
		person.setFirstName("Doe");
		person.setAddress("123 main street");
		person.setAcceptsSpam(true);
		directoryType.getPerson().add(person);
		
		try {
			// create JAXB context and instantiate marshaller
			JAXBContext context = JAXBContext.newInstance(DirectoryType.class);
			Marshaller m = context.createMarshaller();
			m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
			System.out.println("\nMarshalling DirectoryType to console");
			m.marshal(directoryType, System.out);
			
			File tempXml = File.createTempFile("directory-", ".xml");
			//tempXml.deleteOnExit();
			FileOutputStream out = new FileOutputStream(tempXml);
			System.out.println("\nMarshalling DirectoryType to file: " + tempXml.getAbsolutePath());
			m.marshal(directoryType, out);
			out.close();
			
			System.out.println("\nUnmarshalling DirectoryType from file: " + tempXml.getAbsolutePath());
			Unmarshaller um = context.createUnmarshaller();
			ValidationEventCollector validationEventCollector = new ValidationEventCollector();
			um.setEventHandler(validationEventCollector);
			DirectoryType directory2 = (DirectoryType) um.unmarshal(new FileReader(tempXml));
			if(validationEventCollector != null && validationEventCollector.hasEvents()){
				System.out.println("The following validation errors were detected.");
				for( ValidationEvent ve: validationEventCollector.getEvents() ){
			        String msg = ve.getMessage();
			        ValidationEventLocator vel = ve.getLocator();
			        int line = vel.getLineNumber();
			        int column = vel.getColumnNumber();
			        System.err.println( tempXml.getAbsolutePath() + ": " + line + "." + column + ": " + msg ); 
			    }
			}else{
				System.out.println("No validation errors found.");
			}
				
			m.marshal(directory2, System.out);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		System.out.println("Exiting ...");
	}
}
